package com.yuyou.train.admin.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.train.admin.service.IAuthUserService;
import com.yuyou.train.admin.service.ICaptchaService;
import com.yuyou.train.admin.service.ICommSmsVerCodeService;
import com.yuyou.train.admin.service.ILoginService;
import com.yuyou.train.admin.vo.req.ReqLogin;
import com.yuyou.train.admin.vo.req.ReqRegisAndReset;
import com.yuyou.train.admin.vo.resp.RespLogin;
import com.yuyou.train.service.api.admin.entity.AuthUser;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.service.UserAPI;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.CommCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.message.admin.LoginMess;
import com.yuyou.train.util.tool.DateUtil;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.TokenUtil;

@Service
public class LoginServiceImpl implements ILoginService{

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private ICaptchaService captchaService;
	
	@Autowired
	private UserAPI userAPI;
	
	@Autowired
	private ICommSmsVerCodeService commSmsVerCodeService;
	
	@Autowired
	private IAuthUserService authUserService;
	
	@Override
	@Transactional(timeout=60)
	public RespLogin register(ReqRegisAndReset reqRegisAndReset) {
		RespLogin respLogin=new RespLogin();
		ResBoolSimpleInfo<String> resetPassRes = this.resetPass(reqRegisAndReset,true);
		if(!resetPassRes.isSuccess()){
			respLogin.setSuccess(false);
			respLogin.setMessage(resetPassRes.getMessage());
			return respLogin;
		}else{
			User user=userAPI.selectUsersByPhone(reqRegisAndReset.getPhone());
			
			//生成token
	        String token = TokenUtil.GenerateToken();     
	        LoginRedisObj obj=new LoginRedisObj(user.getId(),user.getUsername(),LoginRedisObj.tagEnum.portal.getValue(),user.getType());
	        
	        String userIdKey=stringRedisTemplate.opsForValue().get(user.getId());
	        if(!StringUtils.isEmpty(userIdKey)){
		        stringRedisTemplate.delete(userIdKey);	
	        }
	        stringRedisTemplate.opsForValue().set(token, obj.toJson(), CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);	
	        stringRedisTemplate.opsForValue().set(user.getId(), token, CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);
	        
	        DefindBeanUtils.copyProperties(obj, respLogin);
	        respLogin.setAccessToken(token);
	        respLogin.setSuccess(true);
	        respLogin.setHeadImg(user.getHeadImg());
	        respLogin.setIsFirst(user.getIsFirst());
	        respLogin.setUserId(user.getId());
	        respLogin.setType(user.getType());
			return respLogin;
		}
	}
	
	@Override
	public RespLogin login(ReqLogin reqLogin) {
		RespLogin respLogin=new RespLogin();
		//前台用户导师登录
		if(reqLogin.getPlaform().equals(LoginRedisObj.tagEnum.portal.getValue())){		
			User user=userAPI.selectUsersByPhone(reqLogin.getPhone());
			if(user==null){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
				return respLogin;
			}	
			
			if(StringUtils.isEmpty(user.getPassword())){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_LOGIN_FIRST);
				return respLogin;
			}
			
			if(user.getStatus().equals(UserEnums.status.freeze.getValue())){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_STATUS_FREEZE);
				return respLogin;
			}
			
			if(user.getIsDel().equals(CommEnums.isDel.yes.getValue())){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_STATUS_DEL);
				return respLogin;
			}
			
			//验证码
			RespLogin ver=verifyCode(reqLogin,LoginRedisObj.tagEnum.portal.getValue());
			if(!ver.getSuccess()){
				return ver;
			}
			
			//密码		
			if(reqLogin.getPassword().equalsIgnoreCase(user.getPassword())){				
				//生成token
		        String token = TokenUtil.GenerateToken();     
		        LoginRedisObj obj=new LoginRedisObj(user.getId(),user.getUsername(),LoginRedisObj.tagEnum.portal.getValue(),user.getType());
		        
		        String userIdKey=stringRedisTemplate.opsForValue().get(user.getId());
		        if(!StringUtils.isEmpty(userIdKey)){
			        stringRedisTemplate.delete(userIdKey);	
		        }
		        stringRedisTemplate.opsForValue().set(token, obj.toJson(), CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);	
		        stringRedisTemplate.opsForValue().set(user.getId(), token, CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);
		        
		        DefindBeanUtils.copyProperties(obj, respLogin);
		        respLogin.setAccessToken(token);
		        respLogin.setSuccess(true);
		        respLogin.setHeadImg(user.getHeadImg());
		        respLogin.setIsFirst(user.getIsFirst());
		        respLogin.setUserId(user.getId());
		        respLogin.setType(user.getType());
		        captchaService.cleanOptStat(reqLogin.getPhone(), LoginRedisObj.tagEnum.portal.getValue());
			}else{		
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
				captchaService.opsStat(reqLogin.getPhone(), LoginRedisObj.tagEnum.portal.getValue());
			}
		}	
		
		//后台管理员登录
		if(reqLogin.getPlaform().equals(LoginRedisObj.tagEnum.admin.getValue())){
			
			AuthUser authUser=authUserService.seleteAuthUserByAccount(reqLogin.getPhone());
			if(authUser==null){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
				return respLogin;
			}
						
			if(authUser.getStatus().equals(0)){
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_STATUS_FREEZE);
				return respLogin;
			}
			
			//验证码
			RespLogin ver=verifyCode(reqLogin,LoginRedisObj.tagEnum.admin.getValue());
			if(!ver.getSuccess()){
				return ver;
			}
			//密码		
			if(reqLogin.getPassword().equalsIgnoreCase(authUser.getPassword())){
				//生成token
		        String token = TokenUtil.GenerateToken();     
		        LoginRedisObj obj=new LoginRedisObj(authUser.getId(),authUser.getUsername(),LoginRedisObj.tagEnum.admin.getValue(),"");
		        
		        String userIdKey=stringRedisTemplate.opsForValue().get(authUser.getId());
		        if(!StringUtils.isEmpty(userIdKey)){
			        stringRedisTemplate.delete(userIdKey);	
		        }
		        stringRedisTemplate.opsForValue().set(token, obj.toJson(), CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);	
		        stringRedisTemplate.opsForValue().set(authUser.getId(), token, CommCons.REDIS_EXPIRE_TIME,CommCons.REDIS_EXPIRE_TIME_UNIT);
		        
		        DefindBeanUtils.copyProperties(obj, respLogin);
		        respLogin.setUserId(authUser.getId());
		        respLogin.setAccessToken(token);
		        respLogin.setSuccess(true);
		        captchaService.cleanOptStat(reqLogin.getPhone(), LoginRedisObj.tagEnum.admin.getValue());
			}else{		
				respLogin.setSuccess(false);
				respLogin.setMessage(LoginMess.ERR_UPDATE_PASSWORD);
				captchaService.opsStat(reqLogin.getPhone(), LoginRedisObj.tagEnum.admin.getValue());
			}

			// 更新最后登录时间
			if(respLogin.getSuccess()){
				AuthUser authUserUpdate = new AuthUser();
				authUserUpdate.setId(authUser.getId());
				authUserUpdate.setLoginTime(DateUtil.now());
				authUserService.updateByPrimaryKeySelective(authUserUpdate);
			}
		}
		
		return respLogin;
	}

	

	public RespLogin verifyCode(ReqLogin reqLogin,String loginTag) {
		RespLogin respLogin=new RespLogin();
		boolean need=captchaService.needVerifyCode(reqLogin.getPhone(), loginTag);
		if(need){
			ResBoolSimpleInfo<String> res=captchaService.verifyCode(reqLogin.getToken(), reqLogin.getCaptcha());				
			if(!res.isSuccess()){
				respLogin.setSuccess(false);
				respLogin.setMessage(res.getMessage());
				return respLogin;
			}			
		}
		respLogin.setSuccess(true);
		return respLogin;
	}
	
	
	
	
	@Override
	public ResBoolSimpleInfo<String> resetPass(ReqRegisAndReset reqRegisAndReset,boolean isRegister) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		//手机白名单校验
		User user=userAPI.selectUsersByPhone(reqRegisAndReset.getPhone());
		if(user==null){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_EMPTY_PHONE);
			return res;
		}	
		if(user.getStatus().equals(UserEnums.status.freeze.getValue())){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_STATUS_FREEZE);
			return res;
		}
		
		if(user.getIsDel().equals(CommEnums.isDel.yes.getValue())){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_STATUS_DEL);
			return res;
		}
		
		if(user.getIsFirst()==1 && !isRegister){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_LOGIN_FIRST);
			return res;
		}
		if(user.getIsFirst()==0 && isRegister){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_REGISTER_NOT_FIRST);
			return res;
		}
		
		//短信验证码校验
		ResBoolSimpleInfo<String> smsRes= commSmsVerCodeService.verSmS(reqRegisAndReset.getPhone(),reqRegisAndReset.getSms());
		if(!smsRes.isSuccess()){
			return smsRes;
		}	
		
		//密码是否一致
		if(!reqRegisAndReset.getPassword().equals(reqRegisAndReset.getcPassword())){
			res.setSuccess(false);
			res.setMessage(LoginMess.ERR_PASS_NOT_EQUAL);
			return smsRes;
		}			
			
		String pass=reqRegisAndReset.getPassword();
		userAPI.resetPass(reqRegisAndReset.getPhone(), pass);	
		return ResBoolSimpleInfo.getSuccessInfo();
	}


	

}